var cheerio = require('cheerio');
var fs = require('fs');
var lib = require('../../lib/index.js');
var config = require('./logoConfig.json');

// 1.创建数据链接
var connection = lib.connectionMDC();
connection.on('error', function(err) {
    console.log('db error', err);
    if (err.code === 'PROTOCOL_CONNECTION_LOST') {
        connection = lib.connectionMDC();
    } else {
        throw err;
    }
});

function saveConfig() {
    fs.writeFile('./logoConfig.json', JSON.stringify(config), function(err) {
        if (err) {
            console.log(err);
        } else {
            console.log('config save ok');
        }
    });
}

async function getList() {
    var promiseArr = [];
    // var sql = 'select * from aaa where company_name = "AGU (QINGDAO) LAWN "';
    var sql = 'select * from aaa where Logo = "no supply" limit '+config.index+',20';
    // var sql = 'select * from aaa where company_name = "Dongguan Shengang Precision Metal "';
    connection.query(sql, function(err, result) {
        result.map(function(item) {
            var promiseFun = new Promise((resolve, reject) => {
                console.log(item.company_name);
                item.company_name = item.company_name.trim();
                getDetail(item, resolve, reject);
            });

            promiseArr.push(promiseFun);
        })

        Promise.all(promiseArr).then((values) => {
            console.log(values);
            console.log('成功,采集下一个');
            config.index +=20;
            getList();
            saveConfig();
        }).catch((e) => {
            console.log('promise.all Err');
            // console.log(e);
        });
    });
}
getList();

async function getDetail(data, resolve, reject) {
    var supplyName = data.company_name.split(' ').join('+');
    let listUrl = 'https://www.made-in-china.com/companysearch.do?word=' + supplyName + '&file=&subaction=hunt&style=b&mode=and&code=0&comProvince=nolimit&order=0&isOpenCorrection=1';

    var result = await lib.myRequest(listUrl).catch(function(err) {
        console.log('列表请求出错');
        console.log(err);
    });
    if (!result) {
        resolve({
            code: -1
        })
        return false;
    }
    var $ = cheerio.load(result);

    var detailUrl = '';
    var listNode = $('.search-list .list-node');
    // var listNode = $('.search-list').last().find('.list-node');

    if (listNode.length > 0) {
        // console.log('-----------');
        listNode.each(function() {
            var name = $(this).find('.company-name').text().trim();
            if (name == data.company_name || name.indexOf(data.company_name) > -1 || data.company_name.indexOf(name) > -1) {
                detailUrl = 'https:' + $(this).find('.company-name a').attr('href');
                return false;
            } else {
                updateLogo(data, 'no supply', resolve, {
                    code: -1,
                    msg: '未找到企业'
                })
            }
        });
    } else {
        updateLogo(data, 'no supply', resolve, {
            code: -2,
            msg: '未找到企业'
        })
        return false;
    }

    if (detailUrl) {
        var result2 = await lib.myRequest(detailUrl).catch(function(err) {
            console.log('内容请求出错');
            console.log(err);
            updateLogo(data, 'no supply', resolve, {
                code: -3,
                msg:'企业详情打不开'
            })
            return false;
        });
        var $$ = cheerio.load(result2);
        var logo1 = $$('.sr-comInfo-logo img').attr('data-original');
        var logo2 = $$('.sr-logo-img').attr('src');
        var logo3 = $$('.com-logo img').attr('data-original');
        var logo4 = $$('.com-logo img').attr('src');
        var logo = logo1 || logo2 || logo3 || logo4 ;
        if(logo){
            updateLogo(data, logo, resolve, {
                code: 0
            })
        }else{
            updateLogo(data, 'no logo', resolve, {
                code: -3,
                msg:'没有logo'
            })
        }
    }
}

function updateLogo(data, logo, resolve,resolveData) {
    var sql = 'update aaa set logo="' + logo + '" where id=' + data.id;
    connection.query(sql, function(err, result) {
        resolve(resolveData)
    });
}
